package cn.com.wantools.service.provider;

import cn.com.wantools.model.exchange.ExchangeInfo;
import cn.com.wantools.model.exchange.UcExchangeRate;
import cn.com.wantools.service.UcExchangeRateService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jboot.aop.annotation.Bean;
import io.jboot.db.model.Columns;
import io.jboot.service.JbootServiceBase;

import java.math.BigDecimal;
import java.util.Map;
import java.util.stream.Collectors;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

@Bean
public class UcExchangeRateServiceProvider extends JbootServiceBase<UcExchangeRate> implements UcExchangeRateService {
    @Override
    public ExchangeInfo queryByBaseCurrency(String baseCurrency) {
        UcExchangeRate ucExchangeRate = findFirstByColumns(Columns.create().eq("base_currency", baseCurrency).lt("expired_time", System.currentTimeMillis()));
        if (ucExchangeRate == null) {
            return null;
        }
        ExchangeInfo exchangeInfo = new ExchangeInfo();
        exchangeInfo.setBaseCurrency(baseCurrency);
        exchangeInfo.setExpiredTimestamp(ucExchangeRate.getExpiredTime());
        exchangeInfo.setExchangeMap(
                JSONObject.parseObject(ucExchangeRate.getExchangeRate())
                        .entrySet()
                        .stream()
                        .collect(Collectors.toMap(java.util.Map.Entry::getKey, entry -> new BigDecimal(String.valueOf(entry.getValue())))));
        return exchangeInfo;
    }

    @Override
    public void saveExchangeRate(ExchangeInfo exchangeInfo) {
        UcExchangeRate ucExchangeRate = new UcExchangeRate();
        ucExchangeRate.setExchangeInfo(JSON.toJSONString(exchangeInfo.getExchangeMap()));
        ucExchangeRate.setRemark("");
        ucExchangeRate.setGmtCreate(System.currentTimeMillis());
        ucExchangeRate.setExpiredTime(exchangeInfo.getExpiredTimestamp());
        ucExchangeRate.setBaseCurrency(exchangeInfo.getBaseCurrency());
        saveOrUpdate(ucExchangeRate);
    }
}
